import fs from 'fs-extra'

export interface ReplaceRule {
    searchValue: string
    replaceValue: string
}

export interface ReplaceRuleCfg {
    file: string
    imports?: string[]
    rules: ReplaceRule[]
}
export class RuleParser {
    public async read (ruleFile: string): Promise<ReplaceRuleCfg[]> {
        const out: ReplaceRuleCfg[] = []
        const content = await fs.readFile(ruleFile, 'utf-8')
        const parts = content.split(/(?:\r?\n)+-{12}(?:\r?\n)*/)
        for (const p of parts) {
            if (p === '') continue
            const ruleset = p.split(/(?:\r?\n)+>{12}(?:\r?\n)+/)
            const head = ruleset[0].split(/(?:\r?\n)+/)
            const file = head[0]
            if (file === 'file') continue
            let imports: string[] | undefined = undefined
            if (head.length > 1) {
                imports = head.slice(1)
            }
            const rules: ReplaceRule[] = []
            for (let i = 1, len = ruleset.length; i < len; i++) {
                const pair = ruleset[i].split(/(?:\r?\n)+<{12}(?:\r?\n)+/)
                const searchValue = pair[0]
                const replaceValue = pair[1]
                rules.push({ searchValue, replaceValue })
            }
            if (rules.length > 0) out.push({ file, imports, rules })
        }
        return out
    }
}